<template>
  <div style="display: flex">
    <category-panel title="分类" icon="tree" request="memberCategory" @delClick="delClick" @notClick="notClick"
                    @nodeClick="nodeClick"/>
    <el-container>
      <el-header>
        <div class="report_header" ref="headerHeight">
          <div class="report_header_left"></div>
          <div style="display: flex;">
            <div class="report_header_query">
              <queryShop @queryShopClick='queryShopClick'></queryShop>
            </div>
            <div class="report_header_query">
              <el-select v-model="query.vipId" clearable placeholder="会员等级">
                <el-option
                  v-for="item in vipList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </div>

            <div class="report_header_query">
              <el-select v-model="query.managerId" clearable  filterable placeholder="客户经理" :filter-method="queryManager">
                <el-option v-for="item in managerList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </div>

            <div class="report_header_query">
              <el-select v-model="query.promoterId" clearable  filterable placeholder="推荐人" :filter-method="queryPromoter">
                <el-option
                  v-for="item in promoterList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </div>

<!--            <div class="report_header_query">-->
<!--              <queryMember @queryMemberClick="queryMemberClick"></queryMember>-->
<!--            </div>-->
<!--            <div class="report_header_query">-->
<!--              <el-select v-model="query.paymentPluginId" clearable placeholder="请选择结算方式">-->
<!--                <el-option label="现结客户" value="cashPayPlugin"></el-option>-->
<!--                <el-option label="月结客户" value="debtPayPlugin"></el-option>-->
<!--                <el-option label="代销客户" value="salePayPlugin"></el-option>-->
<!--              </el-select>-->
<!--            </div>-->
<!--            <div class="report_header_query">-->
<!--              <el-select v-model="query.memberType" clearable placeholder="请选择客户类型">-->
<!--                <el-option label="个人客户" value="0"></el-option>-->
<!--                <el-option label="企业客户" value="1"></el-option>-->
<!--                <el-option label="批发客户" value="2"></el-option>-->
<!--              </el-select>-->
<!--            </div>-->
          </div>
          <div style="display: flex;flex-direction: row;justify-content: flex-end;width: 100%;">
            <div style="display: flex;flex-direction: row;flex-wrap: wrap;overflow: hidden;height:41px">

              <div class="report_header_query" style="width:200px">
                <el-input v-model="query.name" prefix-icon="el-icon-search" placeholder="输入编号/名称/手机/地址"/>
              </div>
            </div>
            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="queryClick">查询
            </el-button>
            <el-button style="margin-left: 10px;margin-top: 5px;" size="small" type="primary" @click="addClick"
                       v-permission="['member.add']">新增
            </el-button>
            <!-- <el-button @click="handleDownload" v-permission="['member.export']"  style="margin-left: 10px;margin-top: 5px;" size="mini" type="info" icon="el-icon-plus">导入导出</el-button> -->
            <ExportList2Excel style='margin-top: 5px;' ref="exportList2Excel" @handleExport="handleExport" name="导出"/>
          </div>
        </div>
      </el-header>
      <div class="pd10">
        <el-table ref="table" v-loadMore="[payLoads,'member-list']" @sort-change="sortChange" :data="memberData" border
                  stripe :height="curHeight" style="width: 100%;">
          <el-table-column type="index" width="50" align="center" fixed/>
          <el-table-column sortable label="注册手机" width="120" align="center" headerAlign="center" prop="mobile"/>
          <el-table-column sortable label="客户名称" width="180" align="left" headerAlign="center" prop="name"/>
          <el-table-column sortable label="会员号" width="100" align="center" prop="code" headerAlign="center"/>
          <el-table-column label="所属门店" width="130" align="left" prop="shopName" headerAlign="center"/>
          <el-table-column sortable label="等级" width="80" align="center" headerAlign="center" prop="vip">
            <template slot-scope="scope">
              <span>{{ scope.row.vipName }}</span>
            </template>
          </el-table-column>

          <!-- <el-table-column label="充值卡" width="80" prop="amount" align="right"  headerAlign="center">
            <template slot-scope="scope">
              <span>{{ Number(scope.row.balance).toFixed(2) }}</span>
            </template>
          </el-table-column>

          <el-table-column label="金币" width="80" prop="point" align="right"  headerAlign="center"></el-table-column> -->

          <el-table-column label="消费金额" width="80" prop="amount" align="right" headerAlign="center">
            <template slot-scope="scope">
              <span>{{ Number(scope.row.amount).toFixed(2) }}</span>
            </template>
          </el-table-column>

          <!--<el-table-column label="绩效金额" width="100" align="right" prop="achieve"></el-table-column>-->

          <el-table-column label="地址" width="300" align="left" headerAlign="center">
            <template slot-scope="scope">
              <span>{{ scope.row.address }}</span>
            </template>
          </el-table-column>

          <!--<el-table-column label="备用电话" width="180" align="center" prop="phone" />-->
          <!--<el-table-column label="邮箱" width="150" align="center" prop="email" />-->

          <el-table-column sortable label="最近购买日期" width="160" align="left" prop="nearBuyDate" headerAlign="center">
            <template slot-scope="scope">
              {{ scope.row.nearBuyDate | datetimeFormatter }}
            </template>
          </el-table-column>

          <el-table-column label="会员有效期" width="120" align="center" headerAlign="center">
            <template slot-scope="scope">{{ scope.row.vipExpired | dateFormatter }}</template>
          </el-table-column>

          <el-table-column sortable label="注册时间" width="160" align="center" prop="createDate" headerAlign="center">
            <template slot-scope="scope">
              {{ scope.row.createDate | datetimeFormatter }}
            </template>
          </el-table-column>

          <el-table-column label="功能" align="center" prop="remark" width="140" fixed="right" headerAlign="center">
            <template slot-scope="scope">
              <div style="display:flex">
                <el-tooltip v-show="deleted == false" class="item" effect="dark" content="详情" placement="top-start">
                  <el-button type="primary" size="mini" @click="detailClick(scope.row)">详情</el-button>
                </el-tooltip>
                <el-tooltip class="item" effect="dark" content="报单" placement="top-start"  v-permission="['order.add']" >
                  <el-button type="primary" size="mini" @click="creadorderClick(scope.row)" >报单</el-button>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" align="center" fixed="right" width="80">
            <template slot-scope="scope">
              <div>
                <el-tooltip v-show="deleted == false" v-permission="['member.edit']" class="item" effect="dark"
                            content="编辑" placement="top-start">
                  <a @click="editClick(scope.row)">
                    <i style="color: #409EFF" class="el-icon-edit"/>
                  </a>
                </el-tooltip>
                <el-tooltip v-show="deleted == false" v-permission="['member.del']" class="item" effect="dark"
                            content="删除" placement="top-start">
                  <a style="margin-left: 10px" @click="deleteMember(scope.row)">
                    <i style="color: #F56C6C" class="el-icon-delete"/>
                  </a>
                </el-tooltip>
                <el-tooltip v-show="deleted == true" v-permission="['member.del']" class="item" effect="dark"
                            content="恢复客户" placement="top-start">
                  <a style="margin-left: 10px" @click="restoreMember(scope.row)">
                    <i style="color: #E6A23C" class="el-icon-refresh-right"/>
                  </a>
                </el-tooltip>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-footer class="el-footerBox">
        <pagination v-show="total>0" :total="total" :page.sync="pageNum" :limit.sync="pageSize"
                    @pagination="loadMember"/>
      </el-footer>
    </el-container>
  </div>
</template>

<script>
import permission from '@/directive/permission/index.js' // 权限判断指令
import { list, del, updateMember,memberList } from '@/api/member'
import utils from '../../utils/utils.js'
import {EventBus} from '@/api/eventBus'
import Pagination from '@/components/Pagination'
import CategoryPanel from '@/components/CategoryPanel'
import loadMore from '@/utils/loadMore.js'
import {list as vipList} from "../../api/vip";
import ExportList2Excel from "@/components/ExportList2Excel";
import queryShop from '@/components/Query/queryShop'
import { list as shopList } from '@/api/shop'
import queryMember from '@/components/Query/queryMember'
import { list as sysEmployeeList } from '@/api/sysEmployee'




export default {
  name: 'member-list',
  directives: {permission, loadMore},
  components: {Pagination, CategoryPanel, ExportList2Excel,queryShop,queryMember},
  filters: {
    formatDate: function (value) {
      const date = new Date(value)
      const y = date.getFullYear()
      let MM = date.getMonth() + 1
      MM = MM < 10 ? ('0' + MM) : MM
      let d = date.getDate()
      d = d < 10 ? ('0' + d) : d
      return y + '-' + MM + '-' + d
    },
    watchGender(val) {
      if (val == 0) {
        return '男'
      } else if (val == 1) {
        return '女'
      } else {
        return '隐藏'
      }
    },
    watchVip(val) {
      if (val == 0) {
        return 'vip0'
      } else if (val == 1) {
        return 'vip1'
      } else if (val == 2) {
        return 'vip2'
      } else if (val == 3) {
        return 'vip3'
      } else if (val == 4) {
        return 'vip4'
      } else if (val == 5) {
        return 'vip5'
      }
    }
  },
  data() {
    return {
      printing: 5000,
      memberData: [],
      pageNum: 1,
      pageSize: 20,
      total: 0,
      queryType: true,
      payLoads: '',
      query: {
        name: '',
        phone: '',
        vipId: '',
        address: '',
        paymentPluginId: '',
        memberType:'',
        shopId:'',
        promoterId:'',
        managerId:'',

      },
      keyword: {
        name: '',
        phone: '',
        vipId: '',
        address: '',
        paymentPluginId: '',
        memberType:'',

      },
      queryPhone: '',
      queryName: '',
      curHeight: null,
      excelData: [],
      memberCategoryId: '',
      deleted: false,
      sortField: "", // 排序
      direction: '',
      restoreForm: {
        id: '',
        deleted: false
      },
      vipList: [],
      shopname:'',
      promoterList:[],
      promoterName:'',
      managerList:[],
      managerName:'',

    }
  },
  created() {
    var _this = this
    this.loadMember()
    this.loadVip()
    EventBus.$on('member-add', res => { // 监听新增完毕
      // 更新列表数组
      _this.memberData.splice(0, 0, res)
    })
    EventBus.$on('member-edit', res => { // 监听新增完毕
      // 更新列表数组
      // for (var i = 0; i < _this.memberData.length; i++) {
      //   if (_this.memberData[i].id == res.id) {
      //     _this.memberData[i] = res
      //   }
      // }
      this.loadMember()
    })
  },
  mounted() {
    this.comeIn()
    this.beforeMount()
  },
  activated() {
    this.payLoads = new Date().getTime()
  },
  methods: {
    watchGender(val) {
      if (val == 0) {
        return '男'
      } else if (val == 1) {
        return '女'
      } else {
        return '隐藏'
      }
    },
    handleExport() {
      let _this = this
      var loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      //要导出函数携带的参数
      //要导出函数携带的参数
      let data = {}
      data.tHeader = ["注册时间", "注册手机", "客户名称", "等级", "会员编码", "所属门店", "充值卡", "金币", '消费金额', "所地址", '备用电话', '邮箱', '最近够买日期', '会员有效期']
      data.filterVal = ["createDate", "mobile", "name", "vipName", "code", "shopName", "balance", "point", 'amount', "areaName", 'phone', 'email', 'nearBuyDate', 'vipExpired']
      data.filename = "客户档案列表";
      const params = new URLSearchParams()
      params.append('pageNum', _this.pageNum)
      params.append('pageSize', _this.printing)
      // params.append('phone', _this.keyword.phone)
      //params.append('address',_this.keyword.address)
      params.append('keyword', _this.keyword.name)
      params.append('vipId', _this.keyword.vipId)
      params.append('paymentPluginId', _this.keyword.paymentPluginId)
      params.append('memberCategoryId', _this.memberCategoryId)
      params.append('deleted', _this.deleted)
      params.append('sortField', _this.sortField)
      params.append('direction', this.direction)
      list(params).then(res => {
        //_this.memberData = response.data.data
        data.list = res.data.data
        data.list.forEach(item => {
          item.createDate = utils.dateFormatter(item.createDate)
          item.nearBuyDate = utils.dateFormatter(item.nearBuyDate)
          item.nearBuyDate = utils.dateFormatter(item.vipExpired)
          item.gender = this.watchGender(item.gender)
        })
        // console.log(data.list);
        _this.$refs.exportList2Excel.handleDownload(data);
        loading.close();
        if (data.list.length == this.printing) {
          this.pageNum++
          this.handleExport()
        } else {
          return;
        }
      }).catch(error => {
        _this.$refs.exportList2Excel.unlockLoading()
        loading.close();
        console.log('error!!')
      })
      //_this.$refs.exportList2Excel.handleDownload(data);
    },
    creadorderClick(val) {
      console.log(val);
      this.$router.push({
        path: '/order/add', query: {id: val.id, name: val.name, creationmethod: 'member', type: 'call'}
      })
      EventBus.$emit('order-customer')

    },
    add0(m) {
      return m < 10 ? '0' + m : m
    },
    format(shijianchuo) {
//shijianchuo是整数，否则要parseInt转换
      var time = new Date(shijianchuo);
      var y = time.getFullYear();
      var m = time.getMonth() + 1;
      var d = time.getDate();
      var h = time.getHours();
      var mm = time.getMinutes();
      var s = time.getSeconds();
      return y + '-' + this.add0(m) + '-' + this.add0(d) + ' ' + this.add0(h) + ':' + this.add0(mm) + ':' + this.add0(s);
    },
    beforeMount() {
      window.onresize = () => {
        return (() => {
          if (this.queryType == false) {
            var h = document.documentElement.clientHeight || document.body.clientHeight
            this.curHeight = h - 266// 减去页面上固定高度height
          } else {
            var h = document.documentElement.clientHeight || document.body.clientHeight
            this.curHeight = h - 220// 减去页面上固定高度height
          }
        })()
      }
    },
    comeIn() {
      console.log('222')
      var h = document.documentElement.clientHeight || document.body.clientHeight
      this.curHeight = h - 220// 减去页面上固定高度height
    },
    editClick(row) {
      this.$router.push({
        path: '/member/edit', query: {id: row.id}
      })
    },
    loadMember(val) {
      console.log(val)
      var _this = this
      const params = new URLSearchParams()
      params.append('pageNum', _this.pageNum)
      params.append('pageSize', _this.pageSize)
      // params.append('phone', _this.keyword.phone)
      //params.append('address',_this.keyword.address)
      params.append('keyword', _this.keyword.name)
      params.append('vipId', _this.keyword.vipId)
      params.append('paymentPluginId', _this.keyword.paymentPluginId)
      params.append('memberType', _this.keyword.memberType)
      params.append('memberCategoryId', _this.memberCategoryId)
      params.append('deleted', _this.deleted)
      params.append('sortField', _this.sortField)
      params.append('direction', this.direction)
      params.append('shopId', this.query.shopId)
      params.append('promoterId', this.query.promoterId)
      params.append('managerId', this.query.managerId)
      // params.append('memberType',0)
      list(params).then(response => {
        console.log(response,'6tgueyw')
        _this.memberData = response.data.data
        _this.total = response.data.total
        _this.promoterList = response.data.data
        _this.promoterId = response.data.data.promoterId
        this.loadmanager()
      }).catch(error => {
        console.log('error!!')
      })
    },

    chooseClick() {
      this.queryType = !this.queryType
      if (this.queryType == false) {
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 266// 减去页面上固定高度height
      } else {
        var h = document.documentElement.clientHeight || document.body.clientHeight
        this.curHeight = h - 220// 减去页面上固定高度height
      }
    },
    addClick() {
      this.$router.push({
        path: '/member/add'
      })
    },
    deleteMember(data) {
      console.log(data)
      var _this = this
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        del(data.id).then(response => {
          console.log(response)
          _this.memberData.forEach(function (item, index) {
            if (item.id == data.id) {
              _this.memberData.splice(index, 1)
            }
          })
          _this.$message({
            message: `删除客户${response.content}`,
            offset: 120,
            center: true
          })
        }).catch(error => {
          console.log('error!!')
        })
      }).catch(() => {
      })
    },
    restoreMember(row) {
      console.log(row)
      this.$confirm('确认恢复?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateMember({id: row.id, deleted: false}).then(() => {
          // 更新列表数组
          this.memberData.forEach((item, index) => {
            if (item.id == row.id) {
              this.memberData.splice(index, 1)
              this.$message({message: '已成功恢复', type: 'success'})
            }
          })
        }).catch(() => {
        })
      }).catch(() => {
      })
    },
    queryClick() {
      this.keyword = this.query
      this.pageNum = 1
      this.loadMember()
    },
    resetClick() {
      this.query.phone = ''
      this.query.name = ''
      this.query.vipId = ''
      this.query.address = '',
      this.query.memberType = ''
      this.keyword = this.query
      this.pageNum = 1
      this.loadMember()
    },
    handleDownload() {
      this.$router.push({
        path: "/member/memberExport"
      })
    },
    /* handleDownload() {
      this.prepareExcel()
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['序号', '姓名', '电话', '备用电话', '地址', '邮箱', '性别', '生日', '等级', '可用余额', '冻结余额', '金币购物券']
          const filterVal = ['index', 'name', 'mobile', 'phone', 'areaName', 'email', 'gender', 'birth', 'vip', 'balance', 'freezeBalance', 'point']
          const list = this.excelData
          const data = this.formatJson(filterVal, list)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: this.filename,
            autoWidth: this.autoWidth,
            bookType: this.bookType
          })
        })
    }, */
    prepareExcel() {
      var _this = this
      const params = new URLSearchParams()
      params.append('pageNum', 1)
      params.append('pageSize', 10000)
      params.append('phone', _this.keyword.phone)
      params.append('address', _this.keyword.address)
      params.append('keyword', _this.keyword.name)
      params.append('memberCategoryId', _this.memberCategoryId)
      params.append('deleted', _this.deleted)
      list(params).then(response => {
        let ex = {}
        for (var i = 0; i < response.data.data.length; i++) {
          ex = {
            index: i,
            name: response.data.data[i].name,
            mobile: response.data.data[i].mobile,
            phone: response.data.data[i].phone,
            areaName: response.data.data[i].areaName + response.data.data[i].address,
            email: response.data.data[i].email,
            gender: response.data.data[i].gender,
            birth: response.data.data[i].birth,
            vip: response.data.data[i].vip,
            balance: response.data.data[i].balance,
            freezeBalance: response.data.data[i].freezeBalance,
            point: response.data.data[i].point
          }
          _this.excelData.push(ex)
        }
      }).catch(error => {
        console.log('error!!')
      })
    },
    sortChange(column) {
      console.log(column);
      this.sortField = column.prop;
      if (column.order == "ascending") {
        this.direction = "asc";
      } else {
        this.direction = "desc";
      }
      this.loadMember()
    },
    formatJson(filterVal, jsonData) {
      return jsonData.map(v => filterVal.map(j => v[j]))
    },
    notClick() {
      this.memberCategoryId = 0
      this.deleted = false
      this.loadMember()
    },
    delClick() {
      this.deleted = true
      this.memberCategoryId = ''
      this.loadMember()
    },
    nodeClick(data) {
      this.deleted = false
      this.memberCategoryId = data.id
      this.loadMember()
    },
    detailClick(row) {
      this.$router.push({
        path: '/member/detail', query: {id: row.id}
        // path:'/receiver/list',query:{memberId:row.id}
      })
    },
    loadVip() {
      let params = new URLSearchParams();
      params.append('pageSize', 2000);
      vipList(params).then(response => {
        console.log(response)
        this.vipList = response.data.data
      }).catch(error => {
        console.log('error!!')
      })
    },
    queryShopClick(data){
      console.log(data,'详情')
      this.query.shopId = data.shopId
      this.shopname = data.name
    },
    queryPromoter(query){
      console.log(query)
      this.promoterList = []
      list({ keyword: query }).then(res => {
        res.data.data.forEach((option, index) => {
          this.$set(this.promoterList, index, option)
        })
      }).catch(err => {
        console.log(err)
      })
    },
    loadmanager() {
      var _this = this
      const params = new URLSearchParams()
      params.append('pageNum', _this.pageNum)
      params.append('pageSize', _this.pageSize)
      params.append('managerId', this.query.managerId)
      sysEmployeeList(params).then(res=>{
        console.log(res,'5687y')
        this.managerList = res.data.data
      })
    },
    queryManager(query){
      this.managerList = []
      sysEmployeeList({ keyword: query }).then(res => {
        res.data.data.forEach((option, index) => {
          this.$set(this.managerList, index, option)
        })
      }).catch(err => {
        console.log(err)
      })
    },
  }
}
</script>

<style scoped>
.el-footerBox {
  height: 50px !important;
  line-height: 50px !important;
  border-top: 1px solid #f2f2f2;
}

.app {
  background-color: rgba(248, 248, 248, 0.8);
}

/deep/ .el-header {
  padding: 10px;
  /* height: 100% !important; */
  padding-bottom: 0;
}

.report_header {
  width: 100%;
  min-height: 40px;
  box-sizing: border-box;
  background-color: rgba(248, 248, 248, 0.8);
  display: flex;
  align-items: center;
  padding-bottom: 5px;
  position: relative;
  padding-left: 5px;
  padding-right: 5px;
}

.report_header_left {
  width: 5px;
  height: 100%;
  background-color: #409EFF;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
}

.report_header_date {
  margin-left: 10px;
  width: 250px;
  margin-top: 5px;
}

.report_header_query {
  margin-left: 10px;
  width: 150px;
  margin-top: 5px;
}
</style>
